package com.card.server.controller;

import com.card.server.constants.HttpConstants;
import com.card.server.domain.R;
import com.card.server.domain.UserEmitters;
import com.card.server.model.ro.UserInfo;
import com.card.server.service.IMatchService;
import com.card.server.utils.JsonUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;


/**
 * @author TISNIW
 * @version 1.0
 * @date 2025/5/26 8:17
 * @desc
 */
@RestController
@RequestMapping("/match")
public class MatchController {
    private static final Logger log = LoggerFactory.getLogger(MatchController.class);
    @Autowired
    private IMatchService matchService;


    @RequestMapping("/join")
    public R<String> join(@RequestParam Integer game,@RequestParam Integer table,@RequestParam String id, HttpServletRequest request){
        log.info("用户{}正在加入匹配队列{}，{}",id,game,table);
        return matchService.join(id,game,table);
    }
    @CrossOrigin(origins = "http://192.168.69.26:9012", allowCredentials = "true")
    @GetMapping(value = "/send", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> send(@RequestParam Integer id, HttpServletRequest request, HttpServletResponse response) {
//        response.setContentType("text/event-stream");
//        response.setCharacterEncoding("UTF-8");
//        response.setHeader("Cache-Control", "no-cache");
        log.info("用户获取 see 连接 - {}", id);
        String userId = id.toString();

        // 创建一个 Flux，用于每 2 秒发送一次 "匹配中" 消息
        Flux<String> intervalMessages = Flux.interval(Duration.ofSeconds(1))
                .map(sequence -> String.format("data: { \"status\": \"matching\", \"msg\": \"匹配中... %d\" }\n\n", sequence));

        // 创建一个 Flux，用于注册 emitter 并保持连接
        Flux<String> emitterFlux = Flux.create(emitter -> {
            UserEmitters.userEmitters.put(userId, emitter);
            emitter.onDispose(() -> UserEmitters.userEmitters.remove(userId));
        });

        // 合并两个 Flux：定时消息 + emitter 消息流
        return Flux.merge(intervalMessages, emitterFlux)
                .doOnCancel(() -> UserEmitters.userEmitters.remove(userId));
    }

}
